package csu.web.credit_bank.controller;

import csu.web.credit_bank.pojo.*;
import csu.web.credit_bank.pojo.vo.CourseWithStatusVO;
import csu.web.credit_bank.service.*;
import csu.web.credit_bank.utils.Result;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/courses")
public class CoursesController {

    @Autowired
    private CoursesService coursesService;
    @Autowired
    private CourseResourcesService courseResourcesService;
    @Autowired
    private CourseSelectionsService courseSelectionsService;
    @Autowired
    private UsersService usersService;
    @Autowired
    private ResourceService resourceService;
    @Autowired
    private TeachersService teachersService; //

    @GetMapping("/selections/student/{studentId}")
    public Result<IPage<Map<String, Object>>> getSelectedCoursesWithProgress(
            @PathVariable String studentId,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        IPage<Map<String, Object>> coursePage = coursesService.getSelectedCoursesWithProgress(studentId, page, size);
        return Result.success(coursePage);
    }

    @PostMapping
    public Result<Course> createCourse(
            @RequestPart("course") Course course,
            @RequestPart(value = "imageFile", required = false) MultipartFile imageFile) {
        try {
            Course createdCourse = coursesService.createCourseWithImage(course, imageFile);
            return Result.success("课程创建成功", createdCourse);
        } catch (Exception e) {
            return Result.failure(e.getMessage());
        }
    }

    @GetMapping("/{id}")
    public Result<Course> getCourseById(@PathVariable String id) {
        Course course = coursesService.getById(id);
        if (course == null) {
            return Result.failure("课程不存在");
        }
        // 根据 teacherId 获取教师的 username 和 avatar
        if (StringUtils.hasText(course.getTeacherId())) {
            User user = usersService.getUserById(course.getTeacherId()); // 获取 User 对象
            if (user != null) {
                course.setTeacherUsername(user.getUsername()); // 设置教师的 username

                // 【修改】通过 teacherId 查询 Teachers 表获取头像
                Teachers teacherInfo = teachersService.getById(course.getTeacherId()); //
                if (teacherInfo != null) {
                    course.setTeacherAvatar(teacherInfo.getAvatar()); // 设置教师的 avatar
                } else {
                    course.setTeacherAvatar(null); // 或者设置一个默认头像URL
                }
            }
        }
        return Result.success(course);
    }


    @GetMapping
    public Result<IPage<CourseWithStatusVO>> getCourseList(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String q,
            @RequestParam(required = false) String sortBy,
            @RequestParam(required = false) String currentUserId,
            @RequestParam(required = false) String teacherId
    ) {
        IPage<Course> coursePage = coursesService.searchCourses(page, size, q, sortBy, teacherId);
        List<Course> courseRecords = coursePage.getRecords();

        if (courseRecords == null || courseRecords.isEmpty()) {
            return Result.success(new Page<CourseWithStatusVO>().setRecords(new ArrayList<>()));
        }

        List<String> teacherIds = courseRecords.stream()
                .map(Course::getTeacherId)
                .filter(StringUtils::hasText)
                .distinct()
                .collect(Collectors.toList());

        Map<String, User> userMap = new HashMap<>();
        if (!teacherIds.isEmpty()) {
            List<User> users = usersService.listByIds(teacherIds); //
            userMap = users.stream().collect(Collectors.toMap(User::getId, user -> user)); //
        }

        Map<String, Teachers> teacherInfoMap = new HashMap<>();
        if (!teacherIds.isEmpty()) {
            List<Teachers> teachers = teachersService.listByIds(teacherIds); // 【新增】一次性查询所有教师头像信息
            teacherInfoMap = teachers.stream().collect(Collectors.toMap(Teachers::getUserId, teacher -> teacher)); //
        }


        List<CourseWithStatusVO> resultRecords = new ArrayList<>();
        for (Course course : courseRecords) {
            CourseWithStatusVO vo = new CourseWithStatusVO();
            org.springframework.beans.BeanUtils.copyProperties(course, vo);

            // 设置教师用户名
            User user = userMap.get(course.getTeacherId()); // 从用户Map中获取User对象
            if (user != null) {
                vo.setTeacherUsername(user.getUsername()); //
            } else {
                vo.setTeacherUsername("未知教师");
            }

            Teachers teacherInfo = teacherInfoMap.get(course.getTeacherId()); // 从教师信息Map中获取Teachers对象
            if (teacherInfo != null) {
                vo.setTeacherAvatar(teacherInfo.getAvatar()); //
            } else {
                vo.setTeacherAvatar(null);
            }

            if (StringUtils.hasText(currentUserId)) {
                CourseSelection selection = courseSelectionsService.getSelection(currentUserId, course.getId());
                vo.setIsJoined(selection != null);
            } else {
                vo.setIsJoined(false);
            }
            resultRecords.add(vo);
        }
        IPage<CourseWithStatusVO> resultPage = new Page<>(coursePage.getCurrent(), coursePage.getSize(), coursePage.getTotal());
        resultPage.setRecords(resultRecords);
        return Result.success(resultPage);
    }

    @PutMapping("/{id}")
    public Result<Course> updateCourse(@PathVariable String id, @RequestBody Course course) {
        course.setId(id);
        Course updatedCourse = coursesService.updateCourse(course);
        return updatedCourse != null ? Result.success("课程更新成功", updatedCourse) : Result.failure("课程更新失败");
    }

    @DeleteMapping("/{id}")
    public Result<Void> deleteCourse(@PathVariable String id) {
        boolean success = coursesService.deleteCourse(id);
        return success ? Result.success("课程删除成功") : Result.failure("课程删除失败");
    }


    @PostMapping("/{courseId}/resources")
    public Result<CourseResource> linkResource(@PathVariable String courseId, @RequestBody Map<String, String> payload) {
        String resourceId = payload.get("resourceId");
        if (!StringUtils.hasText(resourceId)) {
            return Result.failure("resourceId 不能为空");
        }
        try {
            CourseResource createdLink = courseResourcesService.createLink(courseId, resourceId);
            return Result.success("资源关联成功", createdLink);
        } catch (Exception e) {
            return Result.failure(e.getMessage());
        }
    }

    @DeleteMapping("/{courseId}/resources/{resourceId}")
    public Result<Void> unlinkResource(@PathVariable String courseId, @PathVariable String resourceId) {
        boolean success = courseResourcesService.deleteLinkByCourseAndResource(courseId, resourceId);
        return success ? Result.success("资源关联解除成功") : Result.failure("资源关联解除失败或关联不存在");
    }

    @GetMapping("/{courseId}/resources")
    public Result<List<CourseResource>> getCourseResources(@PathVariable String courseId) {
        return Result.success(courseResourcesService.getLinksByCourseId(courseId));
    }

    @GetMapping("/{courseId}/full-resources")
    public Result<List<Map<String, Object>>> getCourseFullResources(@PathVariable String courseId) {
        try {
            List<Map<String, Object>> resources = coursesService.getCombinedCourseResourcesWithChapter(courseId);
            return Result.success(resources);
        } catch (Exception e) {
            return Result.failure("获取课程详细资源失败: " + e.getMessage());
        }
    }



    @PostMapping("/{courseId}/selections")
    public Result<CourseSelection> createSelection(@PathVariable String courseId, @RequestBody Map<String, String> payload) {
        String userId = payload.get("userId");
        if (!StringUtils.hasText(userId)) {
            return Result.failure("userId 不能为空");
        }
        try {
            CourseSelection selection = courseSelectionsService.createSelection(userId, courseId);
            return Result.success("选课成功", selection);
        } catch (Exception e) {
            return Result.failure(e.getMessage());
        }
    }

    @DeleteMapping("/{courseId}/selections")
    public Result<Void> deleteSelection(@PathVariable String courseId, @RequestParam String userId) {
        if (!StringUtils.hasText(userId)) {
            return Result.failure("userId 不能为空");
        }
        boolean success = courseSelectionsService.deleteSelection(userId, courseId);
        return success ? Result.success("取消选课成功") : Result.failure("取消选课失败或未选该课程");
    }

    @GetMapping("/{courseId}/selections")
    public Result<List<CourseSelection>> getCourseSelections(@PathVariable String courseId) {
        List<CourseSelection> selections = courseSelectionsService.getSelectionsByCourseId(courseId);
        return Result.success(selections);
    }

    @GetMapping("/search")
    public Result<IPage<Course>> searchCourses(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String q,
            @RequestParam(required = false) String sortBy
    ) {
        IPage<Course> results = coursesService.searchCourses(page, size, q, sortBy);
        return Result.success(results);
    }


    @PostMapping("/{courseId}/resources/withChapter")
    public Result<CourseResource> addResourceToChapter(
            @PathVariable String courseId,
            @RequestBody Map<String, Object> payload) {
        String resourceId = (String) payload.get("resourceId");
        Integer chapter = (Integer) payload.get("chapter");
        String operatorId = (String) payload.get("operatorId");
        if (!StringUtils.hasText(resourceId) || chapter == null || chapter <= 0 || !StringUtils.hasText(operatorId)) {
            return Result.failure("参数不完整或无效");
        }

        csu.web.credit_bank.pojo.Course course = coursesService.getById(courseId);
        if (course == null) {
            return Result.failure(404, "课程不存在");
        }
        if (!operatorId.equals(course.getTeacherId())) {
            return Result.failure(403, "无权限操作：您不是该课程的发布者");
        }
        csu.web.credit_bank.pojo.Resource resource = resourceService.getById(resourceId);
        if (resource == null) {
            return Result.failure(404, "要添加的资源不存在");
        }
        try {
            CourseResource createdLink = courseResourcesService.createOrUpdateLinkWithChapter(courseId, resourceId, chapter);
            return Result.success("资源成功添加到章节", createdLink);
        } catch (Exception e) {
            return Result.failure(e.getMessage());
        }
    }
    @GetMapping("/{courseId}/resources/nextChapter")
    public Result<Integer> getNextChapterNumber(@PathVariable String courseId) {
        if (coursesService.getById(courseId) == null) {
            return Result.failure(404, "课程不存在");
        }
        int nextChapter = courseResourcesService.getMaxChapterByCourseId(courseId) + 1;
        return Result.success(nextChapter);
    }
}